JavaScript Tips
Must Watch!
MustWatch
As you know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS or Wakanda) and has many other implementations.
It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino).
The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.
In this article, I’ll share a set of JavaScript tips, tricks and best practices that should be known by all JavaScript developers regardless of their browser/engine or the SSJS (Server Side JavaScript) interpreter.
Note that the code snippets in this article have been tested in the latest Google Chrome version 30, which uses the V8 JavaScript Engine (V8 3.20.17.15).
Don't forget var
keyword when assigning a variable's value for the first time.
Assignment to an undeclared variable automatically results in a global variable being created.
Avoid global variables.
use ===
instead of ==
The ==
(or !=
) operator performs an automatic type conversion if needed.
The ===
(or !==
) operator will not perform any conversion.
It compares the value and the type, which could be considered faster than ==
.
[10] === 10 // is false
[10] == 10 // is true
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true but true == "a" is false
'' === false // is false
undefined, null
, 0, false, NaN, ''
(empty string) are all falsy.
Use Semicolons for line termination
The use of semi-colons for line termination is a good practice.
You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser.
For more details about why you should use semi-colons, take a look to this artice: http://davidwalsh.name/javascript-semicolons.
Create an object constructor
function Person(firstName, lastName){
this.firstName = firstName;
this.lastName = lastName;
}
var Saad = new Person("Saad", "Mousliki");
Be careful when using typeof, instanceof
and constructor
.
typeof : a JavaScript unary operator used to return a string that represents the primitive type of a variable, don’t forget that typeof null
will return “object”, and for the majority of object types (Array, Date, and others) will return also “object”.
constructor : is a property of the internal prototype property, which could be overridden by code.
instanceof : is another JavaScript operator that check in all the prototypes chain the constructor it returns true if it’s found and false if not.
var arr = ["a", "b", "c"];
typeof arr; // return "object"
arr instanceof Array // true
arr.constructor(); //[]
Create a Self-calling Function
This is often called a Self-Invoked Anonymous Function or Immediately Invoked Function Expression (IIFE).
It is a function that executes automatically when you create it, and has the following form:
(function(){
// some private code that will be executed automatically
})();
(function(a,b){
var result = a+b;
return result;
})(10,20)
Get a random item from an array
var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];
Get a random number in a specific range
This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.
var x = Math.floor(Math.random() * (max - min + 1)) + min;
Generate an array of numbers with numbers from 0 to max
max = 100;
Array.from(Array(max).keys()) //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Shorter version using spread operator.
[...Array(max).keys()] //=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Generate a random set of alphanumeric characters
Math.random().toString(36).slice(2, 12); // max 10 characters
to generate longer strings, regenerate and concat it
Shuffle an array of numbers
var numbers = [5, 45, 120, -2, 28, 40, 12, -8];
numbers.sort(function()
{ return Math.random() - 0.5});
function shuffle() {
var listlen = questionList.length, j = 0, temp;
while (listlen--) {
j = Math.floor(Math.random() * (listlen+1));
temp = questionList[listlen];
questionList[listlen] = questionList[j];
questionList[j] = temp;
}
}
A string trim function
remove whitespace from a string
str.trim()
var str = " javatpoint tutorial website ";
str.trim(); // Javatpoint tutorial website
Append an array to another array
Use the spread operator (...) to unpack the values of the two arrays into a third array.
const arr1 = ['a', 'b'];
const arr2 = ['c', 'd'];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // ['a', 'b', 'c', 'd']
use the concat() method
const arr1 = ['a', 'b'];
const arr2 = ['c', 'd'];
const arr3 = arr1.concat(arr2);
console.log(arr3); // ['a', 'b', 'c', 'd']
You can even pass non-array values to the concat method.
const arr1 = ['a', 'b'];
const arr2 = arr1.concat('c', 'd', ['e']);
console.log(arr2); // ['a', 'b', 'c', 'd', 'e']
use the push() method
const arr1 = ['a', 'b'];
const arr2 = ['c', 'd'];
arr1.push(...arr2);
console.log(arr1); // ['a', 'b', 'c', 'd']
Transform the arguments
object into an array
using spread parameters
function sortArgs(...args) {
return args.sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
Using Array.from:
function sortArgs() {
return Array.from(arguments).sort(function (a, b) { return a - b; });
}
document.body.innerHTML = sortArgs(12, 4, 6, 8).toString();
Verify that a given argument is a number
function isNumber(n){
return !isNaN(parseFloat(n)) && isFinite(n);
}
Verify that a given argument is an array
function isArray(obj){
return Object.prototype.toString.call(obj) === '[object Array]' ;
}
Note that if the toString() method is overridden, you will not get the expected result using this trick.
Or use…
Array.isArray(obj); // its a new Array method
You could also use instanceof
if you are not working with multiple frames.
However, if you have many contexts, you will get a wrong result.
var myFrame = document.createElement('iframe');
document.body.appendChild(myFrame);
var myArray = window.frames[window.frames.length-1].Array;
var arr = new myArray(a,b,10); // [a,b,10]
// instanceof will not work correctly, myArray loses his constructor
// constructor is not shared between frames
arr instanceof Array; // false
Get the max or the min in an array of numbers
var numbers = [5, 458 , 120 , -215 , 228 , 400 , 122205, -85411];
var maxInNumbers = Math.max.apply(Math, numbers);
var minInNumbers = Math.min.apply(Math, numbers);
Empty an array
var myArray = [12 , 222 , 1000 ];
myArray.length = 0; // myArray will be equal to [].
Don't use delete to remove an item from array
Use splice
instead of using delete
to delete an item from an array.
Using delete
replaces the item with undefined
instead of the removing it from the array.
Instead of…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
delete items[3]; // return true
items.length; // return 11
/* items will be equal to [12, 548, "a", undefined × 1, 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
Use…
var items = [12, 548 ,'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' ,2154 , 119 ];
items.length; // return 11
items.splice(3,1) ;
items.length; // return 10
/* items will be equal to [12, 548, "a", 5478, "foo", 8852, undefined × 1, "Doe", 2154, 119] */
The delete method should be used to delete an object property.
Truncate an array using length
Like the previous example of emptying an array, we truncate it using the length
property.
var myArray = [12 , 222 , 1000 , 124 , 98 , 10 ];
myArray.length = 4; // myArray will be equal to [12 , 222 , 1000 , 124].
As a bonus, if you set the array length to a higher value, the length will be changed and new items will be added with undefined
as a value.
The array length is not a read only property.
myArray.length = 10; // the new array length is 10
myArray[myArray.length - 1] ; // undefined
Use logical AND/ OR for conditions
var foo = 10;
foo == 10 && doSomething(); // is the same thing as if (foo == 10) doSomething();
foo == 5 || doSomething(); // is the same thing as if (foo != 5) doSomething();
The logical OR could also be used to set a default value for function argument.
function doSomething(arg1){
arg1 = arg1 || 10; // arg1 will have 10 as a default value if it's not already set
}
Use the map() function method to loop through an array’s items
var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]
Rounding number to N decimal place
var num =2.443242342;
num = num.toFixed(4); // num will be equal to 2.4432
NOTE : the toFixed()
function returns a string and not a number.
Floating point problems
0.1 + 0.2 === 0.3 // is false
9007199254740992 + 1 // is equal to 9007199254740992
9007199254740992 + 2 // is equal to 9007199254740994
Why does this happen? 0.1 +0.2 is equal to 0.30000000000000004.
What you need to know is that all JavaScript numbers are floating points represented internally in 64 bit binary according to the IEEE 754 standard.
For more explanation, take a look to this blog post.
You can use toFixed()
and toPrecision()
to resolve this problem.
Check the properties of an object when using a for-in loop
This code snippet could be useful in order to avoid iterating through the properties from the object's prototype.
for (var name in object) {
if (object.hasOwnProperty(name)) {
// do something with name
}
}
Comma operator
var a = 0;
var b = ( a++, 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99
A comma operator takes two expressions, evaluates them from left to right, and returns the value of the right expression.
For example:
let result = (10, 10 + 20);
console.log(result); // 30
let x = 10;
let y = (x++, x + 1);
console.log(x, y); // 11 12
Cache variables that need calculation or querying
In the case of a jQuery selector, we could cache the DOM element.
var navright = document.querySelector('#right');
var navleft = document.querySelector('#left');
var navup = document.querySelector('#up');
var navdown = document.querySelector('#down');
Verify the argument before passing it to isFinite()
isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true !!!
Avoid negative indexes in arrays
var numbersArray = [1,2,3,4,5];
var from = numbersArray.indexOf("foo") ; // from is equal to -1
numbersArray.splice(from,2); // will return [5]
Make sure that the arguments passed to splice
are not negative.
Serialization and deserialization (working with JSON)
var person = {name :'Saad', age : 26, department : {ID : 15, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Saad","age":26,"department":{"ID":15,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object */
Avoid the use of eval()
or the Function
constructor
Use of eval
or the Function
constructor are expensive operations as each time they are called script engine must convert source code to executable code.
var func1 = new Function(functionCode);
var func2 = eval(functionCode);
Avoid using with()
(The good part)
Using with()
inserts a variable at the global scope.
Thus, if another variable has the same name it could cause confusion and overwrite the value.
Avoid using for-in loop for arrays
Instead of using…
var sum = 0;
for (var i in arrayNumbers) {
sum += arrayNumbers[i];
}
…it's better to use…
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
sum += arrayNumbers[i];
}
As a bonus, the instantiation of i
and len
is executed once because it's in the first statement of the for loop.
Thsi is faster than using…
for (var i = 0; i < arrayNumbers.length; i++)
Why? The length of the array arrayNumbers
is recalculated every time the loop iterates.
NOTE : the issue of recalculating the length in each iteration was fixed in the latest JavaScript engines.
Pass functions, not strings, to setTimeout()
and setInterval()
If you pass a string into setTimeout()
or setInterval()
, the string will be evaluated the same way as with eval
, which is slow.
Instead of using…
setInterval('doSomethingPeriodically()', 1000);
setTimeout('doSomethingAfterFiveSeconds()', 5000);
…use…
setInterval(doSomethingPeriodically, 1000);
setTimeout(doSomethingAfterFiveSeconds, 5000);
Use a switch/case statement instead of a series of if/else
Using switch/case is faster when there are more than 2 cases, and it is more elegant (better organized code).
Avoid using it when you have more than 10 cases.
Use switch/case statement with numeric ranges
Using a switch/case statement with numeric ranges is possible with this trick.
function getCategory(age) {
var category = "";
switch (true) {
case isNaN(age):
category = "not an age";
break;
case (age >= 50):
category = "Old";
break;
case (age <= 20):
category = "Baby";
break;
default:
category = "Young";
break;
};
return category;
}
getCategory(5); // will return "Baby"
Create an object whose prototype is a given object
It's possible to write a function that creates an object whose prototype is the given argument like this…
function clone(object) {
function OneShotConstructor(){};
OneShotConstructor.prototype= object;
return new OneShotConstructor();
}
clone(Array).prototype ; // []
An HTML escaper function
function escapeHTML(text) {
var replacements= {"<": "<", ">": ">","&": "&", """: """};
return text.replace(/[<>&"]/g, function(character) {
return replacements[character];
});
}
Avoid using try-catch-finally inside a loop
The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.
Instead of using…
var object = ['foo', 'bar'], i;
for (i = 0, len = object.length; i <len; i++) {
try {
// do something that throws an exception
}
catch (e) {
// handle exception
}
}
…use…
var object = ['foo', 'bar'], i;
try {
for (i = 0, len = object.length; i <len; i++) {
// do something that throws an exception
}
}
catch (e) {
// handle exception
}
Set timeouts to XMLHttpRequests
You could abort the connection if an XHR takes a long time (for example, due to a network issue), by using setTimeout()
with the XHR call.
var xhr = new XMLHttpRequest ();
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
clearTimeout(timeout);
// do something with response data
}
}
var timeout = setTimeout( function () {
xhr.abort(); // call error callback
}, 60*1000 /* timeout after a minute */ );
xhr.open('GET', url, true);
xhr.send();
As a bonus, you should generally avoid synchronous XHR calls completely.
Deal with WebSocket timeout
Generally when a WebSocket connection is established, a server could time out your connection after 30 seconds of inactivity.
The firewall could also time out the connection after a period of inactivity.
To deal with the timeout issue you could send an empty message to the server periodically.
To do this, add these two functions to your code: one to keep alive the connection and the other one to cancel the keep alive.
Using this trick, you'll control the timeout.
Add a timerID
…
var timerID = 0;
function keepAlive() {
var timeout = 15000;
if (webSocket.readyState == webSocket.OPEN) {
webSocket.send('');
}
timerId = setTimeout(keepAlive, timeout);
}
function cancelKeepAlive() {
if (timerId) {
cancelTimeout(timerId);
}
}
The keepAlive()
function should be added at the end of the onOpen()
method of the webSocket connection and the cancelKeepAlive()
at the end of the onClose()
method.
primitive operations can be faster than function calls
primitive operations can be faster than function calls.
Use VanillaJS.
For example, instead of using…
var min = Math.min(a,b);
A.push(v);
…use…
var min = a < b ? a : b;
A[A.length] = v;
Don't forget to use a code beautifier when coding
Use JSLint and minification (JSMin, for example) before going live.
JavaScript is awesome: Best Resources To Learn JavaScript
Code Academy JavaScript tracks: http://www.codecademy.com/tracks/javascript
Eloquent JavaScript by Marjin Haverbeke: http://eloquentjavascript.net/
Advanced JavaScript by John Resig: http://ejohn.org/apps/learn/
Conclusion
I know that there are many other tips, tricks and best practices, so if you have any ones to add or if you have any feedback or corrections to the ones that I have shared, please adda comment.
Javascript tips and tricks to Optimize Performance
JavaScript or JS helps implement complex things on web pages.
Many of the developers know the importance of an minified Javascript file but few are aware of an Optimized Javascript code.
An optimized code is a combination of smartly programmed logics and small hacks to optimize performance, speed and save time.
Here are sweet 16 JS hacks and tips for developers for optimizing Javascript to improve JS performance and improve execution time without affecting server resources.
Use Array Filter
It is a small hack to filter out bucket of elements from the array pool.
This method creates an array filled with all array elements that pass a test (provided as a function).
According to requirement create a callback function for non-required elements.
In below example the bucket elements are null and are ready to get filtered out.
Example:
schema = ["hi","ihaveboyfriend",null, null, "goodbye"]
schema = schema.filter(function(n) {
return n
});
Output: ["hi","ihaveboyfriend", "goodbye"]
This hack will save some time and lines of codes for developers.
Using String replace function to replace all the values
The String.replace() function allows you to replace strings using String and Regex.
Basically this function replaces the string at its first occurrence.
But to replace all using replaceAll() function, use /g at the end of a Regex:
Example:
var string = "login login";
console.log(string.replace("in", "out")); // "logout login"
console.log(string.replace(/in/g, "out")); //"logout logout"
Use breakpoints and Console for Debugging
With the help of breakpoints or debugging points you can set multiple barriers to rectify source of error at every barrier.
Press F11 for next call function and f8 to resume script execution.
You can also check what dynamic values are generated by a function, using console and can check output on different values.
Convert to floating number without killing performance
Often we use math.floor, math.ceil and math.round for eliminating decimals.
Instead of using them use “~~” to eliminate decimals for a value.
It is also helpful in increasing performance when it comes to micro optimizations in a code.
Example:
Use
~~ (math.random*100)
Instead of
math.round(math.random*100)
Using length to delete empty in an array
This technique will help you in resizing and emptying an array.
For deleting n elements in an Array, use array.length.
array.length = n
See this example:
var array = [1, 2, 3, 4, 5, 6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]
For **emptying array** use
array.length = 0;.
Example:
var array = [1, 2, 3, 4, 5, 6];
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
This technique is mostly preferred over any other methods to resize/unset the array elements and is one of the best javascript practices most of the developers follow.
Merging arrays without causing server load
If your requirement is of merging two arrays, use Array.concat() function
For merging two arrays:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.concat(array2)); // [1,2,3,4,5,6];
This function works best for small arrays.
To merge large arrays we use
Array.push.apply(arr1, arr2)
Reason is using Array.concat() function on large arrays will consume lot of memory while creating a separate new array.
In this case, you can use Array.push.apply(arr1, arr2) which instead will merge the second array in the first one, hence reducing the memory usage.
Example:
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
It will also optimize the performance of your Javascript code irrespective of size of array.
Use splice to delete array elements
This is probably the one of the best optimization tips for javascript.
It optimizes speed of your JS code.
Using splice instead of delete is a good practice, it will save some”null/undefined space” in your code.
The downside of using delete is it will delete the object property, but will not reindex the array or update its length, leaving undefined values.
Also it consumes a-lot of time in execution.
Using splice
Example
myArray = ["a", "b", "c", "d"]
myArray.splice(0, 2) ["a", "b"]
Result: myArray ["c", "d"]
Checking values in an Object
To check whether an object is empty or not, use
Object.keys(YOUR\_OBJECT).length
// 0 returns if object is empty
Following code return the number of elements in an Object.
Cache the variable
Caching the variable tremendously increase javascript performance.
Everytime we use document.getElementById() or getElementsByClassName(), JS travels through all elements repeatedly upon each similar element request.
In Order to boost performance, cache your selections to some variable (if using the same selection multiple times).
Example:
var cached = document.getElementById('someElement');
cached.addClass('cached-element');
It is a simple optimization tip with drastic impact on performance, recommended for processing large arrays in loop(s).
Check this link for performance results.
Use switch case instead of if/else
Generally switch cases are used over if/else statements to perform almost the same tasks.
The fact that in switch statements expression to test is only evaluated once, execution time becomes less for the script compared to if/else where for every if , it has to be evaluated.
Short-circuits conditionals
Short circuiting is when a logical operator doesn't evaluate all its arguments.
The code
if (loggedin) {
welcome\_messege();
}
Make it short by using combination of a verified variable and a function using && (AND operator) in between both.
Now above code can be made in one line
loggedin && welcome\_messege();
Getting the last item in the array
Array.prototype.slice(begin, end) is used to cut arrays when you set the start and end arguments.
But if you don't set the end argument, this function will automatically set the max value for the array.
A smart hack is it can also accept negative values and by setting a negative number as begin argument, you will get the last elements from the array.
var array = [1, 2, 3, 4, 5, 6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]
Default values using || operator
In JS there is a basic rule of having a default value otherwise process will halt at undefined values.
To provide default value in a variable use || to stay away from this most common issue.
var a = a || 'hello'
The developer must check whether there are any conflicting values that might be passed to the function to avoid Bugs.
Beautifying JS code
For beautifying your Javascript code use jsbeautifier.
It formats a clumsy JS code into well structured code.
Code before Beautifying
Code after Beautifying
Checking JS Performance
To check how well a Javascript code is performing and share results use jsperf.
It is easiest way to create and share testcases.
Online javascript editor
Jsfiddle and jsbin is a tool for experimenting with your Javascript code and other web languages.
It is also a code sharing site.
As you type into one of the editor panels the output is generated in real-time in the output panel.
These are some useful hacks and tips for optimizing javascript performance.
It is not mandatory to use them all the time because cases and conditions will vary.
Flatten the array of the array
This tip will help you to flatten a deeply nested array of arrays by using Infinity
in flat
.
var array = [123, 500, [1, 2, [34, 56, 67, [234, 1245], 900]], 845, [30257]] //flatten array of array
array.flat(Infinity) // output:
// [123, 500, 1, 2, 34, 56, 67, 234, 1245, 900, 845, 30257]
Easy Exchange Variables
You probably swap the two variables using a third variable temp
. But this tip will show you a new way to exchange variables using destructuring.
//example 1 var a = 6;
var b = 7; [a,b] = [b,a] console.log(a,b) // 7 6
Sort Alphabetically
Sorting is a common problem in programming and this tip will save your valuable time by writing a long code to sort a string alphabetically.
//sort alphabetically function alphabetSort(arr)
{
return arr.sort((a, b) => a.localeCompare(b));
} let array = ["d", "c", "b", "a"]
console.log(alphabetSort(array)) // ["a", "b", "c", "d"]
Generate Range of Numbers
Suppose you want to generate a number between a specific range. The first approach you will use is the loop. But this tip will save you valuable time by doing it the easy way.
let Start = 1000, End = 1500;
//Generating
[...new Array(End + 1).keys()].slice(Start); Array.from({length: End - Start + 1}, (_,i) => Start + i) // [1000, 1001 .... 1500]
Shorten the Console log
Tired of writing console.log()
again and again? This tip will show how to shorter your console log and speed up your coding.
var c = console.log.bind(document)
c(455)
c("hello world")
Shortening an Array in an easy way
This is an awesome tip for web developers to shorten an array in an easy way. You just need to use the length
method by passing a number that denotes the new size of your array.
let array = ["A", "B", "C", "D", "E", "F"] array.length=2
console.log(array) // ["A", "B"]
Use isNumber
This tip will show how to check whether a value or variable holding a number ( integer, float and etc ) or not.
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } console.log(isNumber(900)) // true
console.log(isNumber(23.98)) // true
console.log(isNumber("JavaScript")) // false
Use isString
This useful tip will show you how to check whether a value or data is in string format or not. This comes in handy when you request data from the server and want to check the data type.
const isString = value => typeof value === 'string'; isString('JavaScript'); // true
isString(345); // false
isString(true); // false
Check Null
In Programming, sometimes we need to check whether a result or data is null.
const CheckNull= value => value === null || value === undefined; CheckNull(null) // true
CheckNull() // true
CheckNull(123) // false
CheckNull("J") // false
Merge Array into One
This tip will be useful when you need to combine the two arrays of any size into one. You need to use the JavaScript concate
method for this.
//Example Code
let arr1 = ["JavaScript", "Python", "C++"]
let arr2 = ["Dart", "Java", "C#"] const mergeArr = arr1.concat(arr2)
console.log(mergeArr) // ["JavaScript", "Python", "C++", "Dart", "Java", "C#"]
Quick Calculate Performance
This tip is personally used most to calculate the performance of my JavaScript program.
const starttime = performance.now();
//some program
const endtime = performance.now(); const totaltime = startTime - endTime
console.log("function takes "+totaltime +" milisecond");
Remove Duplicates
You probably encounter an array with duplicate data and use a loop way to get rid of these duplicates. This tip will help you remove duplicates in an easy way without using any loop.
const ReDuplicates = array => [...new Set(array)]; console.log(ReDuplicates([200,200,300,300,400,500,600,600])) // [200,300,400,600]
Convert Number to Binary
This tip is useful when you need to convert numbers into binary. Take a look at the example code below.
var num = 200
console.log(num.toString(2)) // 11001000 num = 300
console.log(num.toString(2)) //100101100
Character “e” for excessive zeros
This is a time-saving tip for you. You can rid of writing a lot of zeros in JavaScript by replacing all of them with the character “e”.
//normal way
var num = 20000000 //good way
var num2 = 2e7
console.log(num2) //20000000
Make Array Empty
This quick tip will save the time that you put to empty an array. I will show you the quick method to empty in an array using the JavaScript length method.
let array = ["A", "B", "C", "D", "E", "F"] array.length=0
console.log(array) // []
Sum all the values from an array
Suppose we have an array of numbers: let numbers = [2,52,55,5]
.
To get the sum we usually use a for
loop and traverse through the list right
You can easily do that with this line of code: let sum = numbers.reduce((x,y) => return x+y)
.
And you can print the result via console.log(sum)
.
Reduce the length of an array using an array length property
We can reduce the size of the array using the array.length()
method,
Let's see the code for that:
let array = [11,12,12,122,1222]
We now have an array of 5 elements. array.length
will return 5.
Now suppose I want to reduce the length of an array we can just do it by using array.length = 4
now when you print the array your array will consist of [11,12,12,122]
only.
Shuffle array elements
We all need to get random data sometimes. But sometimes we need to get random data from a specific dataset.
At that time we can use the below snippet that will save your time:
Filter unique values
Sometimes we need to filter unique values right. For example, if you are on social media, we have mutual friends. Those mutual fronts are the negation of non-mutual friends i.e unique friends.
For that, we are using sets
.
A set is a collection of well-defined data ie, non-empty, dissimilar, unique.
Comma Operator
The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand.
Swap values with array destructuring
Swapping values has never been easy like this, usually, we introduce a temporary
variable then temporary = b; b = a; a = temporary;
. But that produces a headache, right?
Well, now you can just swap using array destructuring:
Replace if true statements with &&
&& operators are less often used but now you will use more often.
We can make it shorter by using && operator: